import { Vector } from '../../engine/common/vector';
import { IWorld } from '../../engine/ecs/common/world.interface';
import { MovementEventComponent } from '../components/movement-event.component';
import { MovementComponent } from '../../engine/ecs/components/movement.component';
import { Entity } from '../../engine/ecs/entities/entity';
import { System } from '../../engine/ecs/systems/system';

export class PlayerInputSystem extends System {
  constructor(private readonly player: Entity) {
    super();
  }

  onUpdate(world: IWorld, dt: number) {
    const movementComponent = world.findComponentByEntity(this.player, MovementComponent)!;

    const entities = world.findEntitiesByComponent(MovementEventComponent);
    if (entities.length === 0) {
      movementComponent.direction = new Vector(0, 0);
      return;
    }

    let direction = new Vector(0, 0);
    entities.forEach((entity) => {
      const movementEventComponent = world.findComponentByEntity(entity, MovementEventComponent)!;
      direction = direction.add(movementEventComponent.direction);
    });

    movementComponent.direction = direction;
  }
}
